﻿using System;
using System.IO;
using System.Reflection;
using Terraria;
using Terraria.Localization;
using TerrariaApi.Server;
using TShockAPI;

namespace Ruhua
{
    [ApiVersion(2, 1)]
    public class Plugin : TerrariaPlugin
    {
        public override string Description => "更改NPC的名字";
        public override string Name => "如花";
        public override string Author => "hufang360";
        public override Version Version => Assembly.GetExecutingAssembly().GetName().Version;

        /// <summary>
        /// 路径
        /// </summary>
        static readonly string WorkDir = Path.Combine(TShock.SavePath, "Ruhua");
        static readonly string ConfigFile = Path.Combine(WorkDir, "config.json");

        /// <summary>
        /// 配置文件
        /// </summary>
        Config _config;

        public Plugin(Main game) : base(game)
        {
        }

        /// <summary>
        /// 初始时
        /// </summary>
        public override void Initialize()
        {
            // 创建工作目录
            if (!Directory.Exists(WorkDir))
                Directory.CreateDirectory(WorkDir);

            // 读取配置文件
            _config = Config.Load(ConfigFile);
            _config.GenIDs();

            ServerApi.Hooks.NpcSpawn.Register(this, OnNpcSpawn, 1);
        }

        /// <summary>
        /// NPC生成时
        /// </summary>
        void OnNpcSpawn(NpcSpawnEventArgs args)
        {
            NPC npc = Main.npc[args.NpcId];
            if (_config.ids.Contains(npc.netID))
            {
                int index = _config.ids.IndexOf(npc.netID);
                var names = _config.datas[index].names;
                int rnd = Main.rand.Next(names.Count);
                string name = names[rnd];

                npc.GivenName = name;
                NetMessage.SendData(56, -1, -1, NetworkText.FromLiteral(name), args.NpcId, 0f, 0f, 0f, 0);
            }
        }

        /// <summary>
        /// 销毁时
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                ServerApi.Hooks.NpcSpawn.Deregister(this, OnNpcSpawn);
            }
            base.Dispose(disposing);
        }

    }
}